<?php
$response = [];
function reguser($conn,$user_name, $pass_word, $mail,$ip){
if (empty($user_name) || empty($pass_word) || empty($mail)) {
    die("缺少必要的参数");
}
function generateUniqueId($conn, $length = 7) {
    $characters = '0123456789';
    $id = '';
    do {
        $id = '';
        for ($i = 0; $i < $length; $i++) {
            $id .= $characters[rand(0, strlen($characters) - 1)];
        }
        $result = $conn->query("SELECT 1 FROM exam_student WHERE id = '$id'");
        if ($result !== false && $result->num_rows > 0) {
            $id = ''; 
        } else {
            break;
        }
    } while ($id === '');
    return $id;
}

$id = generateUniqueId($conn);
if ($id === false) {
    die("id处理异常");
}
$sql = "SELECT * FROM `exam_student` WHERE username='$user_name'";
$result = $conn -> query($sql);
if ($result !== false && $result->num_rows > 0) {
    die("该用户名已存在");
}

$sqlInsert = "INSERT INTO exam_student (id, username, password,mail) VALUES ('$id', '$user_name', '$pass_word','$mail')";
if ($conn->query($sqlInsert) === TRUE) {
} else {
    die("注册失败");
}

$conn->close();
echo "<script>alert('账号注册成功'); window.location.href = './?juslr';</script>";
exit();
}
?>